import { IFeidaoAiBrowserComponent } from '@feidao/web/interfaces';
import error from '@feidao/web/atom/browser/msgbox/error';
import client_login from '@feidao/web/atom/browser/msg/user-login-with-captcha';
import set_user from '@feidao/web/atom/browser/storage/put';
import { login } from './config';

import a003 from './a003';

export default async function a004(fd: IFeidaoAiBrowserComponent, ...args: any[]) {
	const user_name = fd.data.node.querySelector('[data-feidao-id="user_name"]') as HTMLInputElement;
	if (!user_name.value) {
		return error('请输入用户名');
	}
	const user_pwd = fd.data.node.querySelector('[data-feidao-id="user_pwd"]') as HTMLInputElement;
	if (!user_pwd.value) {
		return error('请输入密码');
	}
	const pic_verification = fd.data.node.querySelector('[data-feidao-id="pic_verification"]') as HTMLInputElement;
	if (!pic_verification.value) {
		return error('请输入验证码');
	}
	// 刷新验证码
	try {
		// 调用登录的通用服务
		const res = await client_login(login, user_name.value, user_pwd.value, pic_verification.value);

		await set_user('user', res);
		await set_user('user_code', res.usercode);
		await set_user('user_name', res.user_name);
		// 跳转到其他页面
		const backurl = fd.data.params.backurl;
		if (backurl) {
			window.location.href = backurl;
		} else {
			window.location.href = 'knowledge-base.html';
		}
	} catch (e) {
		// 刷新验证码
		a003(fd);
		return error(e.message);
	}
}
